{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "内容相同的文件（哈希值: c4ca4238a0b923820dcc509a6f75849b):\n",
      "  C:/szy\\新建文本文档 (2).txt\n",
      "  C:/szy\\新建文本文档 (3).txt\n",
      "内容相同的文件（哈希值: c81e728d9d4c2f636f067f89cc14862c):\n",
      "  C:/szy\\新建文本文档 (4).txt\n",
      "  C:/szy\\新建文本文档.txt\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "import hashlib\n",
    "\n",
    "def calculate_file_hash(file_path):\n",
    "    \"\"\"计算文件的哈希值\"\"\"\n",
    "    hash_func = hashlib.md5()\n",
    "    with open(file_path, 'rb') as file:\n",
    "        for chunk in iter(lambda: file.read(4096), b\"\"):\n",
    "            hash_func.update(chunk)\n",
    "    return hash_func.hexdigest()\n",
    "\n",
    "def find_duplicate_files(directory):\n",
    "    \"\"\"查找目录下内容相同的文件\"\"\"\n",
    "    file_hash_map = {}\n",
    "    for root, dirs, files in os.walk(directory):\n",
    "        for file in files:\n",
    "            file_path = os.path.join(root, file)\n",
    "            file_hash = calculate_file_hash(file_path)\n",
    "            if file_hash in file_hash_map:\n",
    "                file_hash_map[file_hash].append(file_path)\n",
    "            else:\n",
    "                file_hash_map[file_hash] = [file_path]\n",
    "\n",
    "    duplicate_files = {hash_val: paths for hash_val, paths in file_hash_map.items() if len(paths) > 1}\n",
    "    return duplicate_files\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    directory = \"C:/szy\"\n",
    "    duplicate_files = find_duplicate_files(directory)\n",
    "    for hash_val, paths in duplicate_files.items():\n",
    "        print(f\"内容相同的文件（哈希值: {hash_val}):\")\n",
    "        for path in paths:\n",
    "            print(f\"  {path}\")\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.9"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
